import { App } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
import XtxSkeleton from '../skeleton/index.vue'
import XtxCarousel from '../carousel/index.vue'
import XtxMore from '../more/index.vue'
import Bread from '../Bread/index.vue'
import BreadItem from '../Bread/Item.vue'
import XtxCity from '../city/index.vue'
import XtxNumbox from '../numbox/index.vue'
import XtxButton from '../button/index.vue'
import XtxCheckbox from '../checkbox/index.vue'
import XtxMessage from '../message/message.vue'
import XtxDialog from '../dialog/index.vue'
import XtxSwitch from '../switch/index.vue'
import XtxTabs from '../tabs/index.vue'
import XtxTabsPane from '../tabs/pane.vue'

import defaultImg from '@/assets/images/200.png'
export default {
  install(app: App) {
    // 全局注册组件
    app.component(XtxSkeleton.name, XtxSkeleton)
    app.component(XtxCarousel.name, XtxCarousel)
    app.component(XtxMore.name, XtxMore)

    app.component(BreadItem.name, BreadItem)
    app.component(XtxCity.name, XtxCity)
    app.component(XtxNumbox.name, XtxNumbox)
    app.component(XtxButton.name, XtxButton)
    app.component(XtxCheckbox.name, XtxCheckbox)
    app.component(XtxMessage.name, XtxMessage)
    app.component(XtxDialog.name, XtxDialog)
    app.component(XtxSwitch.name, XtxSwitch)
    app.component(XtxTabs.name, XtxTabs)
    app.component(XtxTabsPane.name, XtxTabsPane)

    app.directive('lazy', {
      mounted(el: HTMLImageElement, { value }) {
        // 图片的懒加载逻辑
        // 参数1：回调函数
        // 参数2：可选的配置
        const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {
          if (isIntersecting) {
            // 停止监听
            stop()
            // 给el元素设置src属性
            // value = '123.jpg'
            el.src = value
            // 如果图片加载失败，显示默认的图片
            el.onerror = function () {
              el.src = defaultImg
            }
          }
        })
      }
    })
  }
}